package org.jimmy.tang.concurrent.locks;

import java.util.concurrent.TimeUnit;
import java.util.concurrent.locks.ReentrantLock;

/**
 * @author jimmy
 * 
 */
public class LeftRightDeadLockResolution {
    final ReentrantLock left = new ReentrantLock();
    final ReentrantLock right = new ReentrantLock();

    public void doLeftRight() throws Exception {
        boolean over = false;
        while (!over) {
            if (left.tryLock(1, TimeUnit.SECONDS)) {
                try {
                    if (right.tryLock(1, TimeUnit.SECONDS)) {
                        try {
                            execute1();
                        } finally {
                            right.unlock();
                            over = true;
                        }
                    }
                } finally {
                    left.unlock();
                }
            }
        }
    }

    public void doRightLeft() throws Exception {
        boolean over = false;
        while (!over) {
            if (right.tryLock(1, TimeUnit.SECONDS)) {
                try {
                    if (left.tryLock(1, TimeUnit.SECONDS)) {
                        try {
                            execute2();
                        } finally {
                            left.unlock();
                            over = true;
                        }
                    }
                } finally {
                    right.unlock();
                }
            }
        }
    }

    private void execute2() {
    }

    private void execute1() {
    }
}
